//
//  BaiduMapViewController.m
//  OCUI
//
//  Created by login on 15-7-2.
//
//

#import "BaiduMapViewController.h"
#import <BaiduMapAPI/BMapKit.h>
#import <MapKit/MapKit.h>
#import "DropDrow.h"
#import "Header.h"
#import "PopoverView.h"
#define BAIDUAK @"vMVqyC3prGmBgEtjx9ssb31W"
#define GEO @"94601"
@interface BaiduMapViewController ()<BMKLocationServiceDelegate,BMKCloudSearchDelegate,BMKMapViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    BMKLocationService *_locService;
    BMKCloudSearch* _search;
    BMKMapView* _mapView;
    DropDrow *dd2;
    
    NSMutableArray *POIlocationArray;
    CLLocationCoordinate2D centernPoint;
    
    UIButton *selectMiles;
    
    UITableView *showStationTableView;
    NSArray *tableViewArray;
    UISegmentedControl *segment;
}
@end

@implementation BaiduMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
}
#pragma mark - 初始化百度地图
- (void)initBaiduMap
{
        _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 100, WIDTH, HEIGHT-100)];
        _mapView.delegate = self;
        _mapView.mapType = BMKMapTypeStandard;
        _mapView.userTrackingMode = BMKUserTrackingModeNone;
        [_mapView setShowsUserLocation:YES];
        _mapView.zoomLevel = 16;
        _mapView.isSelectedAnnotationViewFront = YES;
        [self.view addSubview:_mapView];
    

}
#pragma mark - 初始化TableView
- (void)initTableView
{
    
    showStationTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 100, WIDTH, HEIGHT-100) style:UITableViewStylePlain];
    showStationTableView.dataSource = self;
    showStationTableView.delegate = self;
    [self.view addSubview:showStationTableView];
}

#pragma mark - 初始化视图
- (void)initView
{
//    DropDrow *dd1 = [[DropDrow alloc] initWithFrame:CGRectMake(0, 60, WIDTH/2, 50)];
    //    dd1.textField.placeholder = @"请输入联系方式";
//    [dd1.textbutton setTitle:@"区域范围" forState:UIControlStateNormal];
//    NSArray* arr=[[NSArray alloc]initWithObjects:@"200米",@"500米",@"1000米",@"3000米",nil];
//    dd1.tableArray = arr;
//    dd1.delegate = self;
//    dd1.tag = 1111;
//    [self.view addSubview:dd1];
    
    
//    dd2 = [[DropDrow alloc] initWithFrame:CGRectMake(WIDTH/2, 60, WIDTH/2, HEIGHT)];
//    //    dd1.textField.placeholder = @"请输入联系方式";
//    [dd2.textbutton setTitle:@"详细地点" forState:UIControlStateNormal];
//    dd2.tag = 1112;
//    dd2.delegate = self;
//    [self.view addSubview:dd2];

    [self initBaiduMap];
    [_mapView setHidden:NO];
    
    [self initTableView];
    [showStationTableView setHidden:YES];
    
    selectMiles=[UIButton buttonWithType:UIButtonTypeCustom];
    [selectMiles setFrame:CGRectMake(0, 60, WIDTH/2, 40)];
    [selectMiles setBackgroundColor:[UIColor whiteColor]];
    [selectMiles setTitle:@"搜索区域范围" forState:UIControlStateNormal];
    [selectMiles setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [selectMiles setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [selectMiles.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [selectMiles addTarget:self action:@selector(selectMilesClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:selectMiles];

//    UILabel *switchLable = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2, 60, WIDTH/2, 40)];
//    switchLable.backgroundColor = [UIColor whiteColor];
//    switchLable.text = @"显示地图或列表";
//    switchLable.textAlignment = NSTextAlignmentLeft;
//    [self.view addSubview:switchLable];
//    
//    UISwitch *tableViewOrMap = [[UISwitch alloc]initWithFrame:CGRectMake(WIDTH-60, 65, 40, 40)];
//    tableViewOrMap.on = NO;
//    [tableViewOrMap addTarget:self action:@selector(showTableViewOrBaiDuMap:) forControlEvents:UIControlEventValueChanged];
//    [self.view addSubview:tableViewOrMap];
    
    NSArray *segmentedArray = @[@"地图",@"列表"];
    segment = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    segment.frame = CGRectMake(WIDTH/2, 60, WIDTH/2, 40);
    segment.selectedSegmentIndex = 0;
    segment.segmentedControlStyle = UISegmentedControlStylePlain;
    segment.backgroundColor = [UIColor whiteColor];
    segment.tintColor = [UIColor redColor];
    [segment addTarget:self action:@selector(showTableViewOrBaiDuMap:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segment];
    
    
}
#pragma mark - popWindow
-(void)selectMilesClicked:(UIButton *)sender
{
    CGPoint point = CGPointMake(sender.frame.origin.x + sender.frame.size.width/2, sender.frame.origin.y + sender.frame.size.height);
    NSArray *titles = @[@"100米", @"200米", @"500米",@"1000米",@"3000米"];
    PopoverView *pop = [[PopoverView alloc] initWithPoint:point titles:titles images:nil];
    pop.selectRowAtIndex = ^(NSInteger index){
        
        [self whenClickPopWindow:index andTitleArray:titles];
        
    };
    [pop show];
}

- (void)whenClickPopWindow:(NSInteger)index andTitleArray:(NSArray *)array
{
    [selectMiles setTitle:array[index] forState:UIControlStateNormal];
    
    NSString *selectMileStr = [NSString stringWithFormat:@"%@",array[index]];
    NSRange mile = NSMakeRange(0, selectMileStr.length - 1);
    NSString *selectMile = [selectMileStr substringWithRange:mile];
    int miles = [selectMile intValue];
    NSLog(@"%d",miles);
    
    NSString *hostString = @"http://api.map.baidu.com/geosearch/v3/nearby";
    NSString *urlString = [NSString stringWithFormat:@"%@?ak=%@&geotable_id=%@&location=%f,%f&radius=%d&mcode=cn.oc.ui",hostString,BAIDUAK,GEO,_mapView.centerCoordinate.longitude,_mapView.centerCoordinate.latitude,miles];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
        [self performSelectorOnMainThread:@selector(updateMainArray:) withObject:dic waitUntilDone:YES];
        
    }];

}
#pragma mark - 显示TbaleView或者百度地图
- (void)showTableViewOrBaiDuMap:(UISegmentedControl *)show
{

    if (show.selectedSegmentIndex == 1) {
        [_mapView setHidden:YES];
        [showStationTableView setHidden:NO];
    }
    if (show.selectedSegmentIndex == 0) {
        
        [showStationTableView setHidden:YES];
        [_mapView setHidden:NO];
        NSLog(@"%@",POIlocationArray);
        [self addPointAnnotation:POIlocationArray];
    }
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tableViewArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.textLabel.text = tableViewArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
    
    
    NSLog(@"选择的cell  %ld",(long)indexPath.row);
    
    NSString *latitudeString = [NSString stringWithFormat:@"%@",POIlocationArray[indexPath.row][0]];
    NSString *longitudeString = [NSString stringWithFormat:@"%@",POIlocationArray[indexPath.row][1]];
    centernPoint.latitude = [longitudeString doubleValue];//纬度
    centernPoint.longitude = [latitudeString doubleValue];//经度
    [self changeMapCenter];

    [showStationTableView setHidden:YES];
    [_mapView setHidden:NO];
    [segment setSelectedSegmentIndex:0];
}

#pragma mark - 更改地图中心点

- (void)changeMapCenter
{
    BMKCoordinateRegion  region;
    region.center = centernPoint;//中心点
    region.span.latitudeDelta = 0.1;//经度范围（设置为0.1表示显示范围为0.2的纬度范围）
    region.span.longitudeDelta = 0.1;//纬度范围
    [_mapView setRegion:region animated:YES];

}

/*
#pragma mark - DropDrowDelegate

- (void)whenClickDropDrowTableView:(int)selectMile andTag:(NSInteger)tag withIndexRow:(NSInteger)row
{
    NSLog(@"@@@@@@@%d    %ld",selectMile,(long)tag);
    
    if (tag == 1111) {
        NSString *hostString = @"http://api.map.baidu.com/geosearch/v3/nearby";
        NSString *urlString = [NSString stringWithFormat:@"%@?ak=%@&geotable_id=%@&location=%f,%f&radius=%d&mcode=cn.oc.ui",hostString,BAIDUAK,GEO,_mapView.centerCoordinate.longitude,_mapView.centerCoordinate.latitude,selectMile];
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
            [self performSelectorOnMainThread:@selector(updateMainArray:) withObject:dic waitUntilDone:YES];
            
        }];
        
    }

    if (tag == 1112) {
        
        NSLog(@"%@",POIlocationArray[row]);
        
        NSString *latitudeString = [NSString stringWithFormat:@"%@",POIlocationArray[row][0]];
        NSString *longitudeString = [NSString stringWithFormat:@"%@",POIlocationArray[row][1]];
        centernPoint.latitude = [longitudeString doubleValue];//纬度
        centernPoint.longitude = [latitudeString doubleValue];//经度
        
#pragma mark - 更改地图中心点
        BMKCoordinateRegion region;
        region.center = centernPoint;//中心点
        region.span.latitudeDelta = 0.1;//经度范围（设置为0.1表示显示范围为0.2的纬度范围）
        region.span.longitudeDelta = 0.1;//纬度范围
        [_mapView setRegion:region animated:YES];
        
    }
}
*/
#pragma mark - 定位信息
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    _mapView.centerCoordinate = userLocation.location.coordinate;
    [_mapView updateLocationData:userLocation];
    
    [_locService stopUserLocationService];
//    _mapView.showsUserLocation = NO;
    
}

- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    [_mapView setZoomLevel:17];
}

#pragma mark - 更新主线程
- (void)updateMainArray:(NSDictionary *)dict
{
    [dd2.textbutton setTitle:@"详细地点" forState:UIControlStateNormal];
    
    if (dict) {
        POIlocationArray = [NSMutableArray array];
        NSMutableArray *addressArray = [NSMutableArray array];
        
        NSArray *contentsArray = dict[@"contents"];
        for (int i=0; i<contentsArray.count; i++) {
            
            NSArray *array = dict[@"contents"][i][@"location"];
            [POIlocationArray addObject:array];
            
            NSString *addressString = dict[@"contents"][i][@"title"];
            [addressArray addObject:addressString];
        }
        
        for (int i=0; i<addressArray.count; i++) {
            NSLog(@"%@",addressArray[i]);
        }
        
        tableViewArray = [addressArray copy];
        [showStationTableView reloadData];
        [self addPointAnnotation:POIlocationArray];
        
    }
    
}

#pragma mark - 加载成功地图后定位
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView
{
    NSLog(@"地图加载成功");
    
    _locService = [[BMKLocationService alloc]init];
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100];
    
    //初始化BMKLocationService
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    
}
#pragma mark - 根据请求的信息添加大头针
//添加大头针
-(void)addPointAnnotation:(NSArray *)locationArray
{
    
    [_mapView removeAnnotations:_mapView.annotations];
    
    for (int i=0; i<locationArray.count; i++) {
        
        NSString *latitudeString = [NSString stringWithFormat:@"%@",locationArray[i][0]];
        NSString *longitudeString = [NSString stringWithFormat:@"%@",locationArray[i][1]];
        CLLocationCoordinate2D coordinate;
        coordinate.latitude = [longitudeString doubleValue];//纬度
        coordinate.longitude = [latitudeString doubleValue];//经度
        
        NSLog(@"%f  %f",coordinate.latitude,coordinate.longitude);
        
        BMKPointAnnotation *annotation=[[BMKPointAnnotation alloc]init];
        annotation.coordinate=coordinate;
        
        //通过坐标 获取到location
        CLLocation *location=[[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
        //反地理编码
        CLGeocoder *geoCoder=[[CLGeocoder alloc]init];
        annotation.title=@"...";
        [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
            if (!error) {
                //获取位置标记
                CLPlacemark *placeMark=placemarks[0];
                annotation.title=placeMark.name;
                [_mapView addAnnotation:annotation];
                
            }
            //
        }];
    }
    
}
#pragma mark - 大头针视图
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    // 生成重用标示identifier
    NSString *AnnotationViewID = @"AnnotationViewID";
    
    // 检查是否有重用的缓存
    BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        // 设置重天上掉下的效果(annotation)
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
    
    // 设置位置
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
    annotationView.canShowCallout = YES;
    // 设置是否可以拖拽
    annotationView.draggable = NO;
    
    return annotationView;
}
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    [mapView bringSubviewToFront:view];
    [mapView setNeedsDisplay];
}
//
- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    NSLog(@"didAddAnnotationViews");
}

- (void)viewWillAppear:(BOOL)animated
{
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}
- (void)viewWillDisappear:(BOOL)animated
{
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
